<?php
// app/controller/WechatController.php
namespace app\controller;

use think\Request;
use think\Response;

class WechatController
{
    public function index(Request $request)
    {
        // 从GET参数获取微信验证信息
        $signature = $request->param('signature');
        $timestamp = $request->param('timestamp');
        $nonce = $request->param('nonce');
        $echostr = $request->param('echostr');

        // 配置的Token（需与微信后台一致）
        $token = 'c38c7e9f802d954d1e51a1febd59015d';

        // 1. 验证签名
        if ($this->checkSignature($token, $signature, $timestamp, $nonce)) {
            // 直接返回echostr，切勿附加其他内容
            return Response::create($echostr)->contentType('text/plain');
        } else {
            return '签名验证失败';
        }
    }

    /**
     * 验证微信签名
     */
    private function checkSignature($token, $signature, $timestamp, $nonce)
    {
        // 将参数按字典序排序
        $tmpArr = [$token, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode('', $tmpArr);
        $tmpStr = sha1($tmpStr);

        // 与微信传来的signature对比
        return $tmpStr === $signature;
    }
}